import { defineStore } from 'pinia';
import { ref } from 'vue';
import { wxLogin, getUserInfo } from '@/api/user';

export interface UserInfo {
  nickName: string;
  userName: string;
  avatar: string;
  sex: number;
  phonenumber: string;
  weixinOpenId:string
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string>('');
  const userInfo = ref<UserInfo | null>(null);
  const hasAuthorized = ref<boolean>(false);
  const userId = ref<string | number>('');

  // 获取用户信息
  async function fetchUserInfo() {
    try {
      const userInfoRes = await getUserInfo();
      if (userInfoRes) {
        userInfo.value = userInfoRes;
        userId.value = userInfoRes.user.userId;
        // 存储用户信息到本地
        uni.setStorageSync('userInfo', userInfoRes);
        uni.setStorageSync('userId', userInfoRes.user.userId);
      }
      return userInfoRes;
    } catch (error) {
      console.error('获取用户信息失败：', error);
      throw error;
    }
  }

  // 登录
  async function login(code: string, userProfile?: UserInfo) {
    try {
      const res = await wxLogin({ code });
      console.log('登录响应：', res);
      
      // 验证响应数据
      if (!res || !res.token) {
        throw new Error('登录失败：服务器返回数据格式错误');
      }
      
      token.value = res.token;
      if (userProfile) {
        userInfo.value = userProfile;
        hasAuthorized.value = true;
        // 存储用户信息到本地
        uni.setStorageSync('userInfo', userProfile);
        uni.setStorageSync('hasAuthorized', true);
      } else {
        // 如果没有用户信息，设置默认值
        userInfo.value = {
          nickName: '游客',
          avatar: '',
          sex: 0,
          phone: ''
        };
      }
      // 存储token到本地
      uni.setStorageSync('token', res.token);

      // 登录成功后立即获取用户信息
      await fetchUserInfo();

      return res;
    } catch (error) {
      console.error('登录失败：', error);
      // 确保在登录失败时清除状态
      logout();
      throw error;
    }
  }

  // 登出
  function logout() {
    token.value = '';
    userInfo.value = null;
    hasAuthorized.value = false;
    userId.value = '';
    // 清除本地存储
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');
    uni.removeStorageSync('hasAuthorized');
    uni.removeStorageSync('userId');
  }

  // 初始化用户信息
  async function initUserInfo() {
    try {
      const storedToken = uni.getStorageSync('token');
      const storedHasAuthorized = uni.getStorageSync('hasAuthorized');

      if (storedToken) {
        token.value = storedToken;
        // 每次初始化时都重新获取用户信息
        await fetchUserInfo();
      }
      
      if (storedHasAuthorized) {
        hasAuthorized.value = storedHasAuthorized;
      }
    } catch (error) {
      console.error('初始化用户信息失败：', error);
    }
  }

  return {
    token,
    userInfo,
    hasAuthorized,
    userId,
    login,
    logout,
    initUserInfo,
    fetchUserInfo
  };
});
